package com.example.egghttp.retrofit.interceptor;

import com.example.egghttp.retrofit.encrypt.MD5;
import com.pixplicity.easyprefs.library.Prefs;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;

public class Token implements Interceptor {


    public static String getToken() {

        String ttoken = Prefs.getString("token", "");


//        L.d("hcia", "ttoken:" + ttoken);
        return ttoken;


    }

    public static String getUID() {

        String ttoken = Prefs.getString("UID", "-1");


//        L.d("hcia", "ttoken:" + ttoken);
        return ttoken;


    }

    public static boolean isLogin() {
//        L.d("hcia", "getToken()):" + getToken());
//        if (TextUtils.isEmpty(getToken()))
//            return true;

        return Prefs.getString("token", "").length() > 1;
    }

    public static void setToken(String token) {
        Prefs.putString("token", token);

//        L.d("hcia", "Prefs.getAll():" + Prefs.getAll());

        Token.token = token;
    }

    public static void setUID(String UID) {
        Prefs.putString("UID", UID);
//        L.d("hcia", "Prefs.getAll():" + Prefs.getAll());

        Token.UID = token;
    }

    private static String token = "";
    private static String UID = "";
    private static String accessKey = "";
    public static String merchantId = "";

    public static String getAccessKey() {


        String www = Prefs.getString("accessKey", "");


//        L.d("hcia", "ttoken:" + ttoken);
        return www;
//        return accessKey;
    }

    public static String genarateAccessKey() {


        String ssss = ((System.currentTimeMillis() / 1000) + "auerdi-secret");

        String ww = MD5.md5(System.currentTimeMillis() / 1000 + "auerdi-secret").toUpperCase();
        setAccessKey(ww);

//        L.d("hcia", "ttoken:" + ttoken);
        return ww;
//        return accessKey;
    }

    public static void setAccessKey(String accessKey) {

        Prefs.putString("accessKey", accessKey);

        Token.accessKey = accessKey;
    }


    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request original = chain.request();


        Request request;
        if (getToken().length() > 1) {
            request = original.newBuilder()
//                .header("Content-Type", "application/json")
                    .header("access-token", getToken())
                    .header("access-key", getAccessKey())
                    .method(original.method(), original.body())
                    .build();
        } else {
            request = original.newBuilder()
//                .header("Content-Type", "application/json")
                    .method(original.method(), original.body())
                    .build();
        }

        return chain.proceed(request);
    }
}
